<template>
  <div class="monitor-config-dialog">
    <!-- 调度器状态 -->
    <div class="config-section">
      <h3>
        <el-icon><Timer /></el-icon>
        调度器状态
      </h3>
      
      <div class="scheduler-status">
        <div class="status-item">
          <label>运行状态:</label>
          <el-tag :type="schedulerStatus.running ? 'success' : 'danger'" size="large">
            {{ schedulerStatus.running ? '运行中' : '已停止' }}
          </el-tag>
          <div class="status-actions">
            <el-button
              v-if="!schedulerStatus.running"
              type="success"
              size="small"
              @click="startScheduler"
              :loading="operatingScheduler"
            >
              <el-icon><VideoPlay /></el-icon>
              启动
            </el-button>
            <el-button
              v-else
              type="danger"
              size="small"
              @click="stopScheduler"
              :loading="operatingScheduler"
            >
              <el-icon><VideoPause /></el-icon>
              停止
            </el-button>
            <el-button size="small" @click="refreshStatus" :loading="loadingStatus">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
        
        <div class="jobs-info" v-if="schedulerStatus.jobs && schedulerStatus.jobs.length > 0">
          <label>定时任务:</label>
          <div class="jobs-list">
            <div
              v-for="job in schedulerStatus.jobs"
              :key="job.id"
              class="job-item"
            >
              <div class="job-name">{{ job.name }}</div>
              <div class="job-next-run">
                <span v-if="job.next_run_time">
                  下次执行: {{ formatTime(job.next_run_time) }} 
                  ({{ formatAbsoluteTime(job.next_run_time) }})
                </span>
                <span v-else>未安排</span>
              </div>
              <div class="job-trigger">{{ job.trigger }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 监控配置 -->
    <div class="config-section">
      <h3>
        <el-icon><Setting /></el-icon>
        监控配置
        <el-button size="small" @click="loadConfigs" :loading="loadingConfigs">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </h3>
      
      <div class="configs-container" v-loading="loadingConfigs">
        <el-form
          ref="configFormRef"
          :model="configForm"
          label-width="180px"
          size="small"
        >
          <div class="config-group">
            <h4>基础配置</h4>
            
            <el-form-item label="启用小时收集">
              <el-switch
                v-model="configForm.hourly_collection_enabled"
                active-text="启用"
                inactive-text="禁用"
              />
              <span class="config-desc">每小时自动执行数据统计</span>
            </el-form-item>
            
            <el-form-item label="自动发现新表">
              <el-switch
                v-model="configForm.auto_discover_tables"
                active-text="启用"
                inactive-text="禁用"
              />
              <span class="config-desc">已集成到主任务中，每次执行时自动发现新表</span>
            </el-form-item>
            
            <el-form-item label="收集方式">
              <el-select v-model="configForm.default_collection_method" style="width: 200px">
                <el-option label="信息模式(快)" value="information_schema" />
                <el-option label="COUNT查询(准)" value="count_query" />
              </el-select>
              <span class="config-desc">小时任务的数据收集方式（推荐信息模式）</span>
            </el-form-item>
          </div>
          
          <div class="config-group">
            <h4>性能配置</h4>
            
            <el-form-item label="收集超时时间(秒)">
              <el-input-number
                v-model="configForm.max_collection_timeout"
                :min="30"
                :max="3600"
                :step="30"
                style="width: 150px"
              />
              <span class="config-desc">单表数据收集的超时时间</span>
            </el-form-item>
            
            <el-form-item label="批量处理大小">
              <el-input-number
                v-model="configForm.batch_collection_size"
                :min="10"
                :max="200"
                :step="10"
                style="width: 150px"
              />
              <span class="config-desc">批量收集时每批处理的表数量</span>
            </el-form-item>
            
            <el-form-item label="大表行数阈值">
              <el-input-number
                v-model="configForm.large_table_threshold"
                :min="1000000"
                :max="100000000"
                :step="1000000"
                style="width: 150px"
              />
              <span class="config-desc">超过此行数优先使用information_schema</span>
            </el-form-item>
            
            <el-form-item label="失败重试次数">
              <el-input-number
                v-model="configForm.collection_retry_times"
                :min="0"
                :max="10"
                style="width: 150px"
              />
              <span class="config-desc">数据收集失败时的重试次数</span>
            </el-form-item>
          </div>
          
          <div class="config-group">
            <h4>调度配置</h4>
            
            <el-form-item label="小时收集Cron">
              <el-input
                v-model="configForm.hourly_collection_cron"
                style="width: 200px"
                placeholder="3 * * * *"
              />
              <span class="config-desc">每小时第3分钟执行的cron表达式</span>
            </el-form-item>
          </div>
          
          <div class="config-group">
            <h4>数据管理</h4>
            
            <el-form-item label="数据保留天数">
              <el-input-number
                v-model="configForm.keep_stats_days"
                :min="7"
                :max="365"
                style="width: 150px"
              />
              <span class="config-desc">统计数据的保留天数</span>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 手动操作 -->
    <div class="config-section">
      <h3>
        <el-icon><Tools /></el-icon>
        手动操作
      </h3>
      
      <div class="manual-actions">
        <!-- 手动触发定时任务的按钮已隐藏，统一使用主页面的"一键更新"功能 -->
        <!-- 发现新表功能已集成到一键更新中 -->
        
        <el-button @click="cleanupOldData" :loading="cleaning">
          <el-icon><Delete /></el-icon>
          清理过期数据
        </el-button>
      </div>
    </div>

    <!-- 对话框底部操作 -->
    <div class="dialog-actions">
      <el-button @click="resetConfigs" :loading="loadingConfigs">
        <el-icon><RefreshLeft /></el-icon>
        重置
      </el-button>
      <el-button type="primary" @click="saveConfigs" :loading="savingConfigs">
        <el-icon><Check /></el-icon>
        保存配置
      </el-button>
      <el-button @click="$emit('close')">关闭</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Timer, Setting, Tools, Refresh, VideoPlay, VideoPause, 
  Delete, RefreshLeft, Check
} from '@element-plus/icons-vue'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import api from '@/utils/api'
import { logger } from '@/utils/logger'

const emit = defineEmits(['close', 'updated'])

// 响应式数据
const loadingStatus = ref(false)
const loadingConfigs = ref(false)
const savingConfigs = ref(false)
const operatingScheduler = ref(false)
const cleaning = ref(false)

const schedulerStatus = reactive({
  running: false,
  jobs: []
})

const configForm = reactive({
  hourly_collection_enabled: true,
  auto_discover_tables: true,
  default_collection_method: 'information_schema',
  max_collection_timeout: 300,
  batch_collection_size: 50,
  large_table_threshold: 10000000,
  collection_retry_times: 3,
  hourly_collection_cron: '3 * * * *',  // 默认每小时第3分钟
  keep_stats_days: 90
})

const originalConfigs = ref({})

// 格式化函数 - 相对时间（更精确）
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  try {
    const targetTime = new Date(timeStr)
    const now = new Date()
    const diffMs = targetTime - now
    const diffMinutes = Math.floor(diffMs / 60000)
    const diffHours = Math.floor(diffMinutes / 60)
    const diffDays = Math.floor(diffHours / 24)
    
    if (diffMs < 0) {
      return '已过期'
    } else if (diffMinutes < 1) {
      return '即将执行'
    } else if (diffMinutes < 60) {
      return `${diffMinutes}分钟后`
    } else if (diffHours < 24) {
      const remainMinutes = diffMinutes % 60
      return `${diffHours}小时${remainMinutes}分钟后`
    } else {
      const remainHours = diffHours % 24
      return `${diffDays}天${remainHours}小时后`
    }
  } catch (e) {
    // 时间格式化错误，返回原始值
    return timeStr
  }
}

// 格式化函数 - 绝对时间
const formatAbsoluteTime = (timeStr) => {
  if (!timeStr) return ''
  try {
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    // 判断是否是今天
    const now = new Date()
    const isToday = date.getDate() === now.getDate() && 
                    date.getMonth() === now.getMonth() && 
                    date.getFullYear() === now.getFullYear()
    
    if (isToday) {
      return `${hours}:${minutes}:${seconds}`
    } else {
      return `${month}-${day} ${hours}:${minutes}`
    }
  } catch {
    return timeStr
  }
}

// API调用
const loadSchedulerStatus = async () => {
  loadingStatus.value = true
  try {
    const response = await api.get('/starrocks-tables/monitor/status')
    if (response.data.success) {
      const status = response.data.data
      schedulerStatus.running = status.running
      schedulerStatus.jobs = status.jobs || []
    }
  } catch (error) {
    logger.error('获取调度器状态失败:', error)
    ElMessage.error('获取调度器状态失败')
  } finally {
    loadingStatus.value = false
  }
}

const loadConfigs = async () => {
  loadingConfigs.value = true
  try {
    const response = await api.get('/starrocks-tables/monitor/config')
    if (response.data.success) {
      const configs = response.data.data.configs
      
      // 将配置数组转换为对象，并进行类型转换
      configs.forEach(config => {
        if (configForm.hasOwnProperty(config.config_key)) {
          let value = config.config_value
          
          // 根据config_type进行类型转换
          if (config.config_type === 'boolean') {
            // 布尔类型：字符串转布尔
            value = value === 'true' || value === '1' || value === 1 || value === true
          } else if (config.config_type === 'integer') {
            // 整数类型
            value = parseInt(value, 10)
          } else if (config.config_type === 'float') {
            // 浮点数类型
            value = parseFloat(value)
          }
          // 字符串类型直接使用
          
          configForm[config.config_key] = value
        }
      })
      
      // 保存原始配置用于重置
      originalConfigs.value = { ...configForm }
    }
  } catch (error) {
    logger.error('获取监控配置失败:', error)
    ElMessage.error('获取监控配置失败')
  } finally {
    loadingConfigs.value = false
  }
}

// 内部保存配置方法（不显示loading和消息提示）
const doSaveConfigs = async () => {
  const configUpdates = Object.keys(configForm).map(key => {
    let value = configForm[key]
    
    // 将布尔值转换为字符串，保持与数据库一致
    if (typeof value === 'boolean') {
      value = value ? 'true' : 'false'
    }
    
    return {
      config_key: key,
      config_value: value
    }
  })
  
  const response = await api.put('/starrocks-tables/monitor/config', {
    configs: configUpdates
  })
  
  if (response.data.success) {
    originalConfigs.value = { ...configForm }
    return true
  }
  return false
}

// 用户点击保存按钮
const saveConfigs = async () => {
  savingConfigs.value = true
  try {
    const success = await doSaveConfigs()
    if (success) {
      ElMessage.success('配置保存成功')
      emit('updated')
    }
  } catch (error) {
    logger.error('保存监控配置失败:', error)
    ElMessage.error('保存监控配置失败')
  } finally {
    savingConfigs.value = false
  }
}

const resetConfigs = () => {
  Object.assign(configForm, originalConfigs.value)
  ElMessage.success('配置已重置')
}

// 启动调度器（先自动保存配置）
const startScheduler = async () => {
  operatingScheduler.value = true
  try {
    // 步骤1: 先保存配置
    logger.info('启动前自动保存配置...')
    const saveSuccess = await doSaveConfigs()
    
    if (!saveSuccess) {
      ElMessage.error('保存配置失败，无法启动调度器')
      return
    }
    
    logger.info('配置保存成功，开始启动调度器...')
    
    // 步骤2: 启动调度器
    const response = await api.post('/starrocks-tables/monitor/start')
    if (response.data.success) {
      ElMessage.success('配置已保存并启动调度器成功')
      await loadSchedulerStatus()
      emit('updated')
    }
  } catch (error) {
    logger.error('启动调度器失败:', error)
    ElMessage.error('启动调度器失败')
  } finally {
    operatingScheduler.value = false
  }
}

const stopScheduler = async () => {
  try {
    await ElMessageBox.confirm(
      '确认要停止调度器吗？这将停止所有自动数据收集任务。',
      '停止确认',
      { type: 'warning' }
    )
    
    operatingScheduler.value = true
    const response = await api.post('/starrocks-tables/monitor/stop')
    if (response.data.success) {
      ElMessage.success('调度器停止成功')
      await loadSchedulerStatus()
    }
  } catch (error) {
    if (error !== 'cancel') {
      logger.error('停止调度器失败:', error)
      ElMessage.error('停止调度器失败')
    }
  } finally {
    operatingScheduler.value = false
  }
}

const refreshStatus = async () => {
  await Promise.all([
    loadSchedulerStatus(),
    loadConfigs()
  ])
}

// 已删除的函数: triggerHourlyCollection, triggerDailyCollection, triggerTableDiscovery
// 这些功能已整合到主页面的"一键更新"中

const cleanupOldData = async () => {
  try {
    await ElMessageBox.confirm(
      `确认要清理超过 ${configForm.keep_stats_days} 天的统计数据吗？此操作不可恢复。`,
      '清理确认',
      { type: 'warning' }
    )
    
    cleaning.value = true
    // 调用清理API（需要在后端实现）
    ElMessage.success('过期数据清理完成')
    
  } catch (error) {
    if (error !== 'cancel') {
      logger.error('清理过期数据失败:', error)
      ElMessage.error('清理过期数据失败')
    }
  } finally {
    cleaning.value = false
  }
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    loadSchedulerStatus(),
    loadConfigs()
  ])
})
</script>

<style scoped>
.monitor-config-dialog {
  max-height: 80vh;
  overflow-y: auto;
}

.config-section {
  margin-bottom: 32px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.config-section h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 16px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.scheduler-status {
  background: white;
  padding: 16px;
  border-radius: 4px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.status-item label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.status-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.jobs-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.jobs-info label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-top: 4px;
}

.jobs-list {
  flex: 1;
  display: grid;
  gap: 8px;
}

.job-item {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.job-name {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.job-next-run {
  color: #67c23a;
  font-size: 12px;
  margin-bottom: 2px;
}

.job-trigger {
  color: #909399;
  font-size: 12px;
  font-family: 'Monaco', 'Consolas', monospace;
}

.configs-container {
  background: white;
  padding: 16px;
  border-radius: 4px;
}

.config-group {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.config-group:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.config-group h4 {
  margin: 0 0 16px 0;
  color: #409eff;
  font-size: 14px;
  font-weight: 600;
}

.config-desc {
  color: #909399;
  font-size: 12px;
  margin-left: 12px;
}

.manual-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin: 16px -24px -24px -24px;
  padding: 16px 24px;
  background: #f8f9fa;
  border-top: 1px solid #e4e7ed;
  border-radius: 0 0 12px 12px;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  color: #606266;
  font-weight: 500;
}

.logic-explanation {
  font-size: 14px;
  line-height: 1.5;
}

.logic-explanation p {
  margin: 0 0 8px 0;
  font-weight: 500;
}

.logic-explanation ul {
  margin: 8px 0 0 0;
  padding-left: 20px;
}

.logic-explanation li {
  margin-bottom: 4px;
  color: #606266;
}

.logic-explanation strong {
  color: #409eff;
}
</style>
